﻿using System.IO.Ports;
using Modbus.Device;
using Modbus;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Runtime.Remoting.Contexts;
using System.Collections;

namespace CModbusTest
{
    internal class Program2
    {
        private static SerialPort serialport;
        private static ModbusSerialMaster master;
        private static ModbusIpMaster masterIp;
        private static TcpClient tcpclient;
        static void Main(string[] args)
        {
            // 1. 连接到 Modbus 服务器（Modbus TCP）
            tcpclient = new TcpClient();
            tcpclient.Connect(IPAddress.Parse("192.168.110.177"), 502);

            // 2. 获取 Modbus TCP 设备的协议客户端
            masterIp = ModbusIpMaster.CreateIp(tcpclient);
            masterIp.Transport.WriteTimeout = 2000;
            masterIp.Transport.ReadTimeout = 2000;
            masterIp.Transport.WaitToRetryMilliseconds = 500;
            masterIp.Transport.Retries = 3;

            // 3. 读取从站设备的寄存器
            ushort startAddress = 0;  // 寄存器起始地址
            ushort numRegisters = 10; // 读取 10 个寄存器
            try
            {
                // 读取保持寄存器
                ushort[] registers = masterIp.ReadHoldingRegisters(startAddress, numRegisters);

                // 输出结果
                Console.WriteLine("读取到的寄存器值：");
                foreach (var register in registers)
                {
                    Console.WriteLine(register);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"读取错误: {ex.Message}");
            }
        }
    }
}